<script>
import { deepClone } from '@/utils/util'
import storage from '@/utils/storage'
import render from '@/modules/FormCenter/componentsWp/render/render.js'
import {
  caculateNumber,
  caculateTime,
  getNow,
  cacuFutureDate
} from './caculate.js'
const ruleTrigger = {
  'fks-input': 'blur',
  'fks-input-number': 'blur',
  'fks-select': 'change',
  'fks-radio-group': 'change',
  'fks-checkbox-group': 'change',
  'fks-cascader': 'change',
  'fks-time-picker': 'change',
  'fks-date-picker': 'change',
  'fks-rate': 'change',
  'form-upload': 'change',
  'fks-user-selector': 'change',
  'fks-org-selector': 'change',
  'association-form': 'change',
  'detail-table': 'change',
  'fks-amount': 'blur'
}

function colFormItem(h, scheme) {
  const config = scheme.__config__
  const componentDesc = scheme.componentDesc
  const listeners = buildListeners.call(this, scheme)
  let labelWidth = config.labelWidth ? `${config.labelWidth}px` : '100px'
  if (config.showLabel === false) labelWidth = '0'
  if (config.tagAttribute === 'information') {
    return <render conf={scheme} {...{ on: listeners }} />
  } else if (config.tagAttribute === 'detail-table') {
    let ref = 'detailTable-' + scheme.__vModel__
    let detailPermission = this.detailPermission[scheme.__vModel__]
    return (
      <fks-form-item
        label-width={labelWidth}
        prop={scheme.__vModel__}
        span={config.span}
        lead={config.lead ? config.lead : false}
        label={config.showLabel ? config.label : ''}
        key={scheme.__vModel__}
      >
        <render
          detailPermission={detailPermission}
          ref={ref}
          conf={scheme}
          {...{ on: listeners }}
        />
        <div class='component-desc'>{componentDesc}</div>
      </fks-form-item>
    )
  } else {
    let permission = this.flowConfig[scheme.__vModel__]
    return (
      // <fks-col span={config.span}>
      <fks-form-item
        label-width={labelWidth}
        prop={scheme.__vModel__}
        span={this.platform === 'phone' ? 24 : config.span}
        lead={config.lead ? config.lead : false}
        label={config.showLabel ? config.label : ''}
        key={scheme.__vModel__}
      >
        <render permission={permission} conf={scheme} {...{ on: listeners }} />
        <div class='component-desc'>{componentDesc}</div>
      </fks-form-item>
      // </fks-col>
    )
  }
}
function renderForm(h) {
  const { formConfCopy, flowConfig } = this
  if (JSON.stringify(formConfCopy) !== '{}' && flowConfig) {
    return (
      <fks-row gutter={15}>
        <fks-form
          // size={formConfCopy.size}
          // flowConfig={flowConfig}
          disabled={this.type === 'view' ? true : false}
          label-position={this.platform === 'phone' ? 'top' : ''}
          // label-position={formConfCopy.labelPosition}
          label-width={'110px'}
          ref='fksForm'
          // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
          props={{ model: this.formData }}
          rules={this.rules}
        >
          {renderFormItem.call(this, h, formConfCopy.fields, flowConfig)}
        </fks-form>
      </fks-row>
    )
  } else {
    return <fks-skeleton rows={10} animated></fks-skeleton>
  }
}

function renderFormItem(h, elementList, flowConf = {}) {
  if (!elementList.length) {
    return
  }
  return elementList.map((scheme) => {
    //flowConf设置
    //不能直接修改scheme的值，会报死循环的错误，用临时值记录disabled和hide的状态
    let disabledArr = []
    let hideArr = []
    let requiredArr = []
    if (scheme.disabled) {
      disabledArr.push('disabled')
    }
    if (scheme.required) {
      requiredArr.push('required')
    }
    if (flowConf[scheme.__vModel__] === 'modify') {
      disabledArr = []
    }
    if (flowConf[scheme.__vModel__] === 'readonly') {
      disabledArr.push('flowDisabled')
    }
    if (flowConf[scheme.__vModel__] === 'hide') {
      hideArr.push('flowHide')
    }
    //业务规则
    //隐藏
    if (scheme.__config__.attrHide) {
      hideArr.push('attrHide')
    }
    //隐藏>显示，所以只有当scheme.__config__.attrHide为false的时候才显示
    if (scheme.__config__.attrShow && !scheme.__config__.attrHide) {
      hideArr = []
    }
    //只读
    if (scheme.__config__.attrDisabled) {
      disabledArr.push('attrDisabled')
    }
    //当只读不生效，且可编辑生效时，将禁用数组清空
    if (scheme.__config__.attrEditable && !scheme.__config__.attrDisabled) {
      disabledArr = []
    }
    //必填
    if (scheme.__config__.attrRequired) {
      requiredArr.push('attrRequired')
    }
    //当数组长度大于O时，表示生效
    scheme.totalDisabled = disabledArr.length > 0
    scheme.totalRequired = requiredArr.length > 0
    scheme.__config__.hide = hideArr.length > 0
    if (!scheme.__config__.hide) {
      return colFormItem.call(this, h, scheme)
    }
  })
}
/**
 * event为输入值
 * config为当前form-item项配置（defaultValue、label、tag等）
 * scheme为对应 placeholder、disabled、clearable、__vModel__等等
 */
function setValue(event, config, scheme) {
  console.log(scheme)
  //给当前 form-item 表单项绑上 defaultValue
  this.$set(config, 'defaultValue', event)
  //给当前表单 form model对应字段 绑上值
  this.$set(this.formData, scheme.__vModel__, event)
  this.$emit('update:formConf', this.formConfCopy)
  this.$emit('form-data', this.formData)
}

function setSelectorValue(event, config, scheme) {
  let userVal = {
    username: '',
    userfullname: ''
  }
  let deptVal = {
    deptId: '',
    deptName: ''
  }
  if (config.tag === 'fks-user-selector') {
    let userName = []
    let userFullName = []
    event.forEach((item, index) => {
      userName.push(item.userName)
      userFullName.push(item.userFullname)
    })
    userVal.username = userName.join()
    userVal.userfullname = userFullName.join()
    this.$set(config, 'defaultValue', userVal)
    this.$set(this.formData, scheme.__vModel__, userVal)
    this.$emit('update:formConf', this.formConfCopy)
    this.$emit('form-data', this.formData)
  } else if (config.tag === 'fks-org-selector') {
    let deptId = []
    let deptName = []
    event.forEach((item, index) => {
      deptId.push(item.id)
      deptName.push(item.content.name)
    })
    deptVal.deptId = deptId.join()
    deptVal.deptName = deptName.join()
    this.$set(config, 'defaultValue', deptVal)
    this.$set(this.formData, scheme.__vModel__, deptVal)
    this.$emit('update:formConf', this.formConfCopy)
    this.$emit('form-data', this.formData)
  }
}

function setUploadValue(event, config, scheme) {
  this.uploadNumList[scheme.__vModel__] = event
}

// 响应 render.js 中的 vModel $emit事件,在这里调用setValue(或者其他自定义)方法同步更新组件绑定的值
function buildListeners(scheme) {
  const config = scheme.__config__
  const methods = {}
  const listeners = {}
  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach((key) => {
    listeners[key] = (event) => methods[key].call(this, event)
  })
  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = (event) => setValue.call(this, event, config, scheme)
  // 响应 render.js 中的 vModel $emit('change', val)，事件监听器在 `on` 内，选人选部门组件使用，绑定选中值
  if (config.tag === 'fks-user-selector' || config.tag === 'fks-org-selector') {
    listeners.change = (event) => {
      if (event.length > 0) {
        setSelectorValue.call(this, event, config, scheme)
      } else {
        this.$set(config, 'defaultValue', null)
        this.$set(this.formData, scheme.__vModel__, null)
        this.$emit('update:formConf', this.formConfCopy)
        this.$emit('form-data', this.formData)
      }
    }
  } else if (config.tagAttribute === 'upload') {
    // 响应 render.js 中的 vModel $emit('fileChange', val)
    listeners.fileChange = (event) => {
      setUploadValue.call(this, event, config, scheme)
    }
  } else if (config.tagAttribute === 'detail-table') {
    listeners.detailTableChange = (event) => {
      setValue.call(this, event, config, scheme)
    }
  } else if (config.tagAttribute === 'association-form') {
    listeners.associationFormChange = (event) => {
      setValue.call(this, event, config, scheme)
    }
  } else if (config.tagAttribute === 'associate-data') {
    // 关联数据组件打开关联数据选择弹窗
    listeners.handleClickAssociate = (event) => {
      this.$emit('openAssociate', event)
    }
  } else if (config.tagAttribute === 'address-selector') {
    listeners.addressChange = (event) => {
      setValue.call(this, event, config, scheme)
    }
  }
  return listeners
}
//判断富文本内容是否为空
function isEmpty(value) {
  if (!value) {
    return true
  }
  let parseValue = JSON.parse(value)
  if (
    parseValue.length === 1 &&
    parseValue[0].children.length === 1 &&
    parseValue[0].children[0].text.trim() === ''
  ) {
    return true
  }
  return false
}
export default {
  name: 'Parser',
  componentName: 'Parser',
  components: {
    render
  },
  props: {
    platform: {
      type: String,
      default: 'pc'
    },
    formConf: {
      type: Object,
      required: true
    },
    flowConf: {
      type: Object,
      required: false,
      default: () => {
        return {}
      }
    },
    noRules: {
      type: Boolean,
      required: false
    },
    //明细表组件流程节点配置
    detailPermission: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const data = {
      formConfCopy: deepClone(this.formConf),
      formData: {},
      rules: {},
      conditionString: '', // 组件的条件
      flowConfig: deepClone(this.flowConf),
      uploadNumList: {}, // 上传组件上传个数列表（用于上传校验）
      type: this.$route.params.type
    }
    this.initFormData(data.formConfCopy.fields, data.formData)
    if (!this.noRules) {
      this.buildRules(data.formConfCopy.fields, data.rules)
    }
    return data
  },
  computed: {
    formDataCopy() {
      return deepClone(this.formData)
    }
  },
  watch: {
    formDataCopy: {
      handler(newVal, oldVal) {
        this.getCaculate(this.formData)
        //监听的是整个formData，需要过滤和表单属性功能无关的表单项
        for (let key in newVal) {
          let newValItem = JSON.stringify(newVal[key])
          let oldValItem = JSON.stringify(oldVal[key])
          //数据没变直接跳过此次循环
          if (newValItem === oldValItem) {
            continue
          }
          //数据不同是再看该数据是否和表单属性功能相关
          for (let ruleId in this.formAttrFields) {
            if (this.formAttrFields[ruleId].indexOf(key) > -1) {
              this.formAttrSetting(ruleId)
            }
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.formConfCopy.fields && this.formConfCopy.fields.length > 0) {
      //将跟表单属性相关的表单项存下来，方便watch中去做过滤
      //formAttrFields= {规则1:[表单项1,表单项2],规则2:[表单项2,表单项3]}
      let formAttrFields = {}
      this.formConfCopy?.formAttr?.forEach((item) => {
        formAttrFields[item.id] = []
        item.rules.forEach((rule) => {
          formAttrFields[item.id].push(rule.__vModel__)
        })
      })
      this.formAttrFields = formAttrFields
      // 初始化时，要执行一次业务规则
      for (let key in this.formDataCopy) {
        //数据不同是再看该数据是否和表单属性功能相关
        for (let ruleId in this.formAttrFields) {
          if (this.formAttrFields[ruleId].indexOf(key) > -1) {
            this.formAttrSetting(ruleId)
          }
        }
      }
    }
  },
  methods: {
    formAttrSetting(ruleId) {
      let rule = this.formConfCopy.formAttr.find((item) => {
        return item.id === ruleId
      })
      let result = this.caculateRules(rule.rules)
      // console.log(result)
      //如果条件为true,执行动作
      if (result) {
        this.handleActions(rule.actionList, ruleId)
      }
      //条件为false,移除动作
      else {
        this.removeActions(rule.actionList, ruleId)
      }
    },
    caculateRules(rules) {
      let result = rules.reduce((total, current, currentIndex) => {
        //第一条规则的值作为初始值
        if (currentIndex === 0) {
          total = total && this.getRuleResult(current)
        } else {
          // && 和 ||是根据前一个规则的spliceType决定
          if (current.spliceType === '&&') {
            total = total && this.getRuleResult(current)
          } else if (current.spliceType === '||') {
            total = total || this.getRuleResult(current)
          }
        }
        return total
      }, true)
      return result
    },
    getRuleResult(ruleItem) {
      let tagAttribute = ruleItem.tagAttribute

      if (
        tagAttribute === 'select' ||
        tagAttribute === 'radio' ||
        tagAttribute === 'check-box'
      ) {
        //下拉框,单选框组,多选框组
        return this.selectResult(ruleItem)
      } else if (tagAttribute === 'input' || tagAttribute === 'comment') {
        //单行文本或多行文本
        return this.inputResult(ruleItem)
      } else if (
        tagAttribute === 'count' ||
        tagAttribute === 'amount' ||
        tagAttribute === 'number'
      ) {
        return this.numberResult(ruleItem)
      }
      //开关
      else if (tagAttribute === 'form_switch') {
        return this.switchResult(ruleItem)
      } else if (tagAttribute === 'date' || tagAttribute === 'time') {
        return this.dateResult(ruleItem)
      } else if (tagAttribute === 'user-selector') {
        return this.userResult(ruleItem)
      } else if (tagAttribute === 'org-selector') {
        return this.orgResult(ruleItem)
      }
    },
    selectResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let value = ruleItem.value
      let fieldValue = this.formData[vModel]
      switch (rule) {
        case '为空': {
          //数组类型的数据通过长度是否为零判断是否为空
          if (Array.isArray(fieldValue)) {
            return fieldValue.length === 0
          } else {
            return fieldValue === ''
          }
        }
        case '不为空': {
          //数组类型的数据通过长度是否为零判断是否为空
          if (Array.isArray(fieldValue)) {
            return fieldValue.length > 0
          } else {
            return fieldValue !== ''
          }
        }
        case '是':
          return value.indexOf(fieldValue) > -1
        case '不是':
          return value.indexOf(fieldValue) === -1
        case '包含': {
          //下拉选择多选
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.indexOf(value[i]) > -1) {
              return true
            }
          }
          return false
        }
        case '不包含': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.indexOf(value[i]) > -1) {
              return false
            }
          }
          return true
        }
      }
    },
    inputResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let value = ruleItem.value
      let fieldValue = this.formData[vModel]
      switch (rule) {
        case '为空': {
          return fieldValue === ''
        }
        case '不为空': {
          return fieldValue !== ''
        }
        case '包含': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.indexOf(value[i]) > -1) {
              return true
            }
          }
          return false
        }
        case '不包含': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.indexOf(value[i]) > -1) {
              return false
            }
          }
          return true
        }
        case '是': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue === value[i]) {
              return true
            }
          }
          return false
        }
        case '不是': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue === value[i]) {
              return false
            }
          }
          return true
        }
        case '开头为': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.startsWith(value[i])) {
              return true
            }
          }
          return false
        }
        case '结尾为': {
          for (let i = 0; i < value.length; i++) {
            if (fieldValue.endsWith(value[i])) {
              return true
            }
          }
          return false
        }
      }
    },
    numberResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let value = Number(ruleItem.value)
      let value2 = Number(ruleItem.value2)
      let fieldValue = Number(this.formData[vModel])
      switch (rule) {
        case '为空': {
          return fieldValue === ''
        }
        case '不为空': {
          return fieldValue !== ''
        }
        case '在范围内': {
          return fieldValue >= value && fieldValue <= value2
        }
        case '不在范围内': {
          return fieldValue > value2 || fieldValue < value
        }
        case '=':
          return fieldValue === value
        case '≠':
          return fieldValue !== value
        case '>':
          return fieldValue > value
        case '<':
          return fieldValue < value
        case '≥':
          return fieldValue >= value
        case '≤':
          return fieldValue <= value
      }
    },
    switchResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      // let value = ruleItem.value
      let fieldValue = this.formData[vModel]
      switch (rule) {
        case '开启': {
          return fieldValue === '开启'
        }
        case '关闭': {
          return fieldValue === '关闭'
        }
      }
    },
    dateResult(ruleItem) {
      this.$dayjs(fieldValue).unix()
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let value = this.$dayjs(ruleItem.value).unix()
      let value2 = this.$dayjs(ruleItem.value2).unix()
      let fieldValue = this.$dayjs(this.formData[vModel]).unix()
      switch (rule) {
        case '为空': {
          return this.formData[vModel] === ''
        }
        case '不为空': {
          return this.formData[vModel] !== ''
        }
        case '是': {
          return fieldValue === value
        }
        case '不是': {
          return fieldValue !== value
        }
        case '早于': {
          return fieldValue < value
        }
        case '晚于': {
          return fieldValue > value
        }
        case '在范围内': {
          return fieldValue >= value && fieldValue <= value2
        }
        case '不在范围内': {
          return fieldValue < value || fieldValue > value2
        }
      }
    },
    userResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let userfullname = ruleItem.value
      let username = ruleItem.value2
      let fieldValue = this.formData[vModel]
      switch (rule) {
        case '为空': {
          return fieldValue === null
        }
        case '不为空': {
          return fieldValue !== null
        }
        case '是': {
          return username.indexOf(fieldValue?.username) > -1
        }
        case '不是': {
          return username.indexOf(fieldValue?.username) === -1
        }
        case '包含': {
          if (!fieldValue) {
            return false
          }
          if (!fieldValue.username) {
            return false
          }
          let arr = username.split(',')
          for (let i = 0; i < arr.length; i++) {
            if (fieldValue.username.indexOf(arr[i]) > -1) {
              return true
            }
          }
          return false
        }
        case '不包含': {
          if (!fieldValue) {
            return true
          }
          if (!fieldValue.username) {
            return true
          }
          let arr = username.split(',')
          for (let i = 0; i < arr.length; i++) {
            if (fieldValue.username.indexOf(arr[i]) > -1) {
              return false
            }
          }
          return true
        }
      }
    },
    orgResult(ruleItem) {
      let vModel = ruleItem.__vModel__
      let rule = ruleItem.rule
      let deptName = ruleItem.value
      let deptId = ruleItem.value2
      let fieldValue = this.formData[vModel]
      switch (rule) {
        case '为空': {
          return fieldValue === null
        }
        case '不为空': {
          return fieldValue !== null
        }
        case '是': {
          return fieldValue?.deptId === deptId
        }
        case '不是': {
          return fieldValue?.deptId !== deptId
        }
      }
    },
    handleActions(actionList, ruleId) {
      actionList.forEach((action) => {
        this.handleAction(action, ruleId)
      })
    },
    handleAction(action, ruleId) {
      //提示错误跟表单项无关,直接单独处理
      if (action.actionType === '提示错误') {
        this.$message.error(action.actionLabel)
        return
      }
      let formConfCopy = deepClone(this.formConfCopy)
      let fields = formConfCopy.fields
      let field = fields.find((item) => {
        return item.__vModel__ === action.actionField
      })
      //执行动作前，给field加上默认的effectRules
      if (!field.effectRules) {
        field.effectRules = {}
      }
      //记录影响该动作的所有规则id
      if (!field.effectRules[action.actionType]) {
        field.effectRules[action.actionType] = []
      }
      field.effectRules[action.actionType].push(ruleId)
      switch (action.actionType) {
        case '隐藏': {
          field.__config__.attrHide = true
          break
        }
        case '显示': {
          field.__config__.attrShow = true
          break
        }
        case '只读': {
          field.__config__.attrDisabled = true
          break
        }
        case '可编辑': {
          field.__config__.attrEditable = true
          break
        }
        case '必填': {
          field.__config__.attrRequired = true
        }
      }

      this.formConfCopy = formConfCopy
    },
    removeActions(actionList, ruleId) {
      actionList.forEach((action) => {
        this.removeAction(action, ruleId)
      })
    },
    removeAction(action, ruleId) {
      if (action.actionType === '提示错误') {
        return
      }

      let formConfCopy = deepClone(this.formConfCopy)
      let fields = formConfCopy.fields

      let field = fields.find((item) => {
        return item.__vModel__ === action.actionField
      })
      //需要field.effectRules[action.actionType]有值，说明该动作生效过，才能继续执行清除动作的逻辑，否则不执行
      if (field.effectRules && field.effectRules[action.actionType]) {
        //从  field.effectRules[action.actionType]找到等于ruleId的值，并去除掉
        field.effectRules[action.actionType] = field.effectRules[
          action.actionType
        ].filter((item) => {
          return item !== ruleId
        })
        //如果field.effectRules[action.actionType]的长度大于0，说明有其他的规则对该动作仍然生效，不清除动作，直接return
        if (field.effectRules[action.actionType].length > 0) {
          this.formConfCopy = formConfCopy
          return
        }
        //清除动作
        switch (action.actionType) {
          case '隐藏': {
            field.__config__.attrHide = false
            break
          }
          case '显示': {
            field.__config__.attrShow = false
            break
          }
          case '只读': {
            field.__config__.attrDisabled = false
            break
          }
          case '可编辑': {
            field.__config__.attrEditable = false
            break
          }
          case '必填': {
            field.__config__.attrRequired = false
          }
        }
        this.formConfCopy = formConfCopy
      }
    },
    // 数字组件函数计算新的值
    getCaculate(val) {
      if (this.formConfCopy.fields) {
        let countConfig = this.formConfCopy.fields.filter((item) => {
          return (
            item.__config__.tagAttribute === 'count' ||
            item.__config__.tagAttribute === 'amount' ||
            item.__config__.tagAttribute === 'number'
          )
        })

        let timeConfig = this.formConfCopy.fields.filter((item) => {
          return (
            item.__config__.tagAttribute === 'time' ||
            item.__config__.tagAttribute === 'date'
          )
        })
        let cacuValue = 0
        timeConfig.forEach((item) => {
          if (item.__config__.formula.type === 'now') {
            cacuValue = getNow(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'cacuDate') {
            cacuValue = cacuFutureDate(item, val)
            this.setCacuValue(item, val, cacuValue)
          }
        })
        countConfig.forEach((item) => {
          if (item.__config__.formula.type === 'sum') {
            cacuValue = caculateNumber(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'product') {
            cacuValue = caculateNumber(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'avg') {
            cacuValue = caculateNumber(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'max') {
            cacuValue = caculateNumber(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'min') {
            cacuValue = caculateNumber(item, val)
            this.setCacuValue(item, val, cacuValue)
          } else if (item.__config__.formula.type === 'dateDif') {
            let value = caculateTime(item, val)
            cacuValue = this.dealNumber(value, item)
            this.setCacuValue(item, val, cacuValue)
          }
        })
      }
    },
    setCacuValue(item, val, cacuValue) {
      val[item.__vModel__] = String(cacuValue)
      this.$set(item.__config__, 'defaultValue', String(cacuValue))
    },
    dealNumber(value, item) {
      if (item.limit && value) {
        let valueArr = value.toString().split('.')
        if (valueArr.length != 1) {
          let newValue = Number('0.' + valueArr[1].slice(0, 10)) > 0.5 ? 1 : 0.5
          return parseInt(valueArr[0]) + newValue
        } else {
          return parseInt(valueArr[0])
        }
      } else {
        return parseInt(value)
      }
    },
    // 父组件CustomForm要用到的方法，封装到Parser组件
    dealResponseFormObj(formObj) {
      formObj.forEach((item, index) => {
        // if (
        //   Object.prototype.toString.call(item.__config__.defaultValue) ==
        //     '[object String]' &&
        //   item.__config__.defaultValue.length > 0
        // ) {
        let userSelected =
          item.__config__.tagAttribute == 'user-selector' &&
          item.__config__.defaultValue.username == null
        let deptSelected =
          item.__config__.tagAttribute == 'org-selector' &&
          item.__config__.defaultValue.deptId == null
        if (
          item.__config__.tagAttribute == 'time-range' ||
          item.__config__.tagAttribute == 'date-range' ||
          item.__config__.tag == 'fks-cascader' ||
          item.__config__.tag == 'fks-checkbox-group' ||
          (item.__config__.tagAttribute == 'select' && item.multiple) ||
          item.__config__.tagAttribute === 'address-selector'
        ) {
          if (
            Object.prototype.toString.call(item.__config__.defaultValue) ==
              '[object String]' &&
            item.__config__.defaultValue.length > 0
          ) {
            let val = item.__config__.defaultValue.split(',')
            if (
              ['notify', 'address-selector'].indexOf(
                item.__config__.tagAttribute
              ) > -1
            ) {
              item.__config__.defaultValue = val
            } else {
              // 使用split的时候数组中数字会转换为字符串，导致页面中组件回显问题
              item.__config__.defaultValue = val.map((e) => {
                let dealE = Number(e)
                if (!isNaN(dealE)) {
                  e = Number(e)
                }
                return e
              })
            }
          } else {
            item.__config__.defaultValue =
              item.__config__.tagAttribute == 'time-range' ? null : [] // 解决时间范围组件无默认值无法选中bug
          }
          if (item.__config__.tagAttribute == 'notify') {
            item.__slot__.options[1].disabled = storage.get('smsAvailable')
              ? false
              : true
            item.__slot__.options[2].disabled = storage.get('mailAvailable')
              ? false
              : true
          }
        } else if (userSelected || deptSelected) {
          item.__config__.defaultValue = {}
        } else if (item.__config__.tag == 'detail-table') {
          item.__config__.defaultValue = JSON.parse(
            item.__config__.defaultValue
          )
        }
      })
    },
    //自由表单组件回填数据
    fillFormData(form, data) {
      form.fields.forEach((item) => {
        const val = data[item.__vModel__]
        if (
          val &&
          JSON.stringify(val) !== '[]' &&
          JSON.stringify(val) !== '{}'
        ) {
          if (
            item.__config__.tagAttribute === 'time-range' ||
            item.__config__.tagAttribute === 'date-range' ||
            item.__config__.tag === 'fks-cascader' ||
            item.__config__.tag === 'fks-checkbox-group' ||
            item.__config__.tag == 'detail-table' ||
            item.__config__.tag == 'association-form' ||
            (item.__config__.tagAttribute === 'select' && item.multiple) ||
            item.__config__.tagAttribute === 'address-selector'
          ) {
            if (Object.prototype.toString.call(val) == '[object Array]') {
              item.__config__.defaultValue = val
            } else {
              let transValue = val.split(',')
              item.__config__.defaultValue = JSON.parse(transValue)
            }
          } else if (
            item.__config__.tag === 'fks-slider' ||
            item.__config__.tag === 'fks-rate'
          ) {
            // data中的val都是string类型
            item.__config__.defaultValue =
              typeof val === 'string' ? JSON.parse(val) : val
          } else if (
            item.__config__.tag === 'fks-user-selector' ||
            item.__config__.tag === 'fks-org-selector' ||
            item.__config__.tag === 'write-info'
          ) {
            // 选人选组件应为对象
            item.__config__.defaultValue =
              typeof val === 'string' ? JSON.parse(val) : val
          } else {
            item.__config__.defaultValue = val
          }
        }
      })
    },
    initFormData(componentList, formData) {
      if (componentList) {
        componentList.forEach((cur) => {
          const config = cur.__config__
          if (cur.__vModel__) {
            if (
              typeof config.defaultValue === 'object' &&
              JSON.stringify(config.defaultValue) == '{}'
            ) {
              formData[cur.__vModel__] = null
            } else {
              formData[cur.__vModel__] = config.defaultValue
            }
          }
          if (config.children) this.initFormData(config.children, formData)
        })
        this.$emit('form-data', formData)
      }
    },
    buildRules(componentList, rules) {
      if (!componentList) {
        return
      }
      componentList.forEach((cur) => {
        const config = cur.__config__
        if (Array.isArray(config.regList)) {
          if (config.tag === 'form-upload' && config.required) {
            let obj = `${cur.__vModel__}`
            rules[obj] = [
              {
                type: Number,
                required: true,
                validator: (rule, value, callback) => {
                  if (
                    !this.uploadNumList[cur.__vModel__] ||
                    (this.uploadNumList[cur.__vModel__] == 0 && rule.required)
                  ) {
                    callback(new Error('请上传文件'))
                  } else {
                    callback()
                  }
                },
                trigger: 'change'
              }
            ]
          } else if (config.tag === 'association-form' && config.required) {
            let obj = `${cur.__vModel__}`
            rules[obj] = [
              {
                required: true,
                validator: (rule, value, callback) => {
                  if (value.length < 1 && rule.required) {
                    callback(new Error('请选择关联表单'))
                  } else {
                    callback()
                  }
                },
                trigger: 'change'
                // trigger: 'change'
              }
            ]
          } else if (config.tag === 'detail-table' && config.required) {
            let obj = `${cur.__vModel__}`
            rules[obj] = [
              {
                required: true,
                validator: (rule, value, callback) => {
                  callback()
                },
                trigger: 'change'
                // trigger: 'change'
              }
            ]
          } else if (config.tag === 'wang-editor' && config.required) {
            let __vModel__ = cur.__vModel__
            rules[__vModel__] = [
              {
                required: true,
                trigger: 'blur',
                // trigger: 'blur',
                validator: (rule, value, callback) => {
                  let empty = isEmpty(value)
                  if (empty) {
                    callback(new Error('该字段必填'))
                  } else {
                    callback()
                  }
                }
              }
            ]
          } else {
            if (config.required) {
              const required = {
                required: config.required,
                message: cur.placeholder
              }
              if (Array.isArray(config.defaultValue)) {
                required.type = 'array'
                required.message = `请至少选择一个${config.label}`
              }
              required.message === undefined &&
                (required.message = `${config.label}不能为空`)
              config.regList.push(required)
            }
            rules[cur.__vModel__] = config.regList.map((item) => {
              item.pattern && (item.pattern = eval(item.pattern))
              item.trigger = ruleTrigger && ruleTrigger[config.tag]
              return item
            })
          }
        }
        if (config.children) this.buildRules(config.children, rules)
      })
    },
    resetForm() {
      this.formConfCopy = deepClone(this.formConf)
      this.initFormData(this.formConfCopy.fields, this.formData)
    },
    submitForm() {
      this.$refs.fksForm.validate((valid) => {
        if (!valid) return false
        // 触发sumit事件
        this.$emit('submit', this.formData)
        return true
      })
    }
  },
  render(h) {
    return renderForm.call(this, h)
  }
}
</script>
<style lang="scss" scoped>
::v-deep .fks-range-separator {
  min-width: 32px;
}
</style>
